package com.sgb.kjwl.viewmodel.transport;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.databinding.ObservableField;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.model.entity.transport.GoodsHallFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapSourcesEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.TransportRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.view.ui.fragment.transport.GoodsHallListFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow.DEFAULT_GOODS_TYPE;

public class GoodsListAndMapModel extends BaseViewModel {

    private GoodsHallListFragment goodsHallListFragment;
    private TransportRepertory repertory;
    public ObservableField<GoodsHallFilterEntity> filterEntity = new ObservableField<>(new GoodsHallFilterEntity());
    public ObservableField<GoodsHallFilterEntity> timeFilterEntity = new ObservableField<>(new GoodsHallFilterEntity());
    public ObservableField<GoodsSourceLocationEntity> sendLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsSourceLocationEntity> purposeLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsInfoTypeEntity3> goodsType = new ObservableField<>(new GoodsInfoTypeEntity3());
    public ObservableField<GoodsInfoTypeEntity3> goodsSecondType = new ObservableField<>(new GoodsInfoTypeEntity3());
    private Map map;
    public boolean isMap = false;//是否是图查页面，如果是pattern为0的时候请求全部货源
    private int pageSize = 10;
    public String radius;

    public GoodsListAndMapModel(GoodsHallListFragment goodsHallListFragment, TransportRepertory repertory) {
        this.goodsHallListFragment = goodsHallListFragment;
        this.repertory = repertory;
    }

    public void getGoodsTypeData() {
        NewAPIManager.getInstance().getLogisticsAPI().getGoodsTypeChooseData().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;
                List<GoodsInfoTypeEntity3> carTypeList = response.body().getData() != null ? response.body().getData() : new ArrayList<>();
                if (response.body().getState().equals("ok")) {
                    GoodsInfoTypeEntity3 type = new GoodsInfoTypeEntity3("", "不限");
                    carTypeList.add(0, type);

                    if (goodsHallListFragment != null) {
                        goodsHallListFragment.refreshGoodsTypeData(carTypeList);
                    }
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.GOODS_INFO_TYPE, new Gson().toJson(carTypeList));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });

    }

    public void getCarTypeAndCarLengthList(String goodsTypeNo) {
        if (TextUtils.isEmpty(goodsTypeNo) || goodsTypeNo.equals(DEFAULT_GOODS_TYPE)) {
            goodsTypeNo = "";
        }
        DialogHelper.showProgressDialog(goodsHallListFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        String finalGoodsTypeNo = goodsTypeNo;
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLengthList(goodsTypeNo).enqueue(new Callback<BaseEntity<List<CarTypeAndCarLength>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Response<BaseEntity<List<CarTypeAndCarLength>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    goodsHallListFragment.setCarTypeAndCarLength(finalGoodsTypeNo, response.body().getData());
                } else {
                    MToast.showToast(goodsHallListFragment.getActivity(), response.body().getState());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void getGoodsSuccess(BaseEntity<ProListEntity<List<GoodsInfoEntity>>> data) {
        if (data == null)
            return;
        if (data.getState().equals(APIManager.RESPONSE_OK)) {
            if (data.getData() == null) {
                MToast.showToast(goodsHallListFragment.getActivity(), "暂无数据");
                return;
            }
            if (data.getData().getList() == null) {
                MToast.showToast(goodsHallListFragment.getActivity(), "暂无数据");
                return;
            }
            Log.v("sourceList", data.getData().getList().toString());
            if (goodsHallListFragment != null)
                goodsHallListFragment.refreshGoodsInfoList(data.getData().getList(), data.getData().isLastPage());
        } else {
            MToast.showToast(goodsHallListFragment.getActivity(), data.getState());
        }
    }

    private void getGoodsFail(Throwable t) {
        t.printStackTrace();
        goodsHallListFragment.finishRefreshOrLoadMore();
        MToast.showToast(goodsHallListFragment.getActivity(), t.getMessage());
    }


    public void getAddressModel() {
        if (goodsHallListFragment.getActivity() == null) {
            return;
        }
        DialogHelper.showProgressDialog(goodsHallListFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {

                if (data != null && data.size() > 0) {
                    DialogHelper.dismissProgressDialog();
                    goodsHallListFragment.initAddressData(data);
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {

            }
        });
    }


    /**
     * 根据城市区域查询经纬度
     *
     * @param context
     * @param provinceName
     * @param cityName
     */
    public void getLocation(Context context, String provinceName, String cityName) {
        if (TextUtils.isEmpty(cityName) || cityName.equals("不限")) {
            cityName = "";
        }
        GeocodeSearch geocoderSearch = new GeocodeSearch(context);
        GeocodeQuery query = new GeocodeQuery(provinceName + cityName, cityName);
        geocoderSearch.getFromLocationNameAsyn(query);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int code) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                if (i == AMapException.CODE_AMAP_SUCCESS) {
                    if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null
                            && geocodeResult.getGeocodeAddressList().size() > 0) {
                        GeocodeAddress address = geocodeResult.getGeocodeAddressList().get(0);
                        double latitude = address.getLatLonPoint().getLatitude();//纬度
                        double longitude = address.getLatLonPoint().getLongitude();//经度
                        //回调UI
                        goodsHallListFragment.refreshGoodsByLatLng(new LatLng(latitude, longitude));
                    } else {
                        MToast.showToast(goodsHallListFragment.getContext(), "地址名出错");
                    }
                } else {
                    ToastUtil.show(context, com.sgb.alimaplibrary.R.string.no_result);
                }
            }
        });
    }

    public void goodsSourceStatusCheck(String no, int position) {
        NewAPIManager.getInstance().getLogisticsAPI().goodsSourceStatusCheck(no).enqueue(new Callback<BaseEntity<CheckStateEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<CheckStateEntity>> call, Response<BaseEntity<CheckStateEntity>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    goodsHallListFragment.checkGoodsState(position, response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<CheckStateEntity>> call, Throwable t) {

            }
        });
    }

    public void getSourceList(int pageNum, int pattern, String keyWord) {
        if (map == null) {
            map = new HashMap();
        } else {
            map.clear();
        }

        //封装请求参数
        map.put("keyWord", keyWord);
        //2.2.0.2 需求改版：//只有竞价货运才传pattern=1，其他情况（货运大厅）不传pattern，表示查全部
        if (pattern == 1) {
            map.put("pattern", 1);
        }
//        if (!isMap) {
//            map.put("pattern", pattern);
//        } else if (pattern == 1) {
//            map.put("pattern", 1);
//        }

        map.put("page", pageNum);
        map.put("limit", pageSize);

        if (null != timeFilterEntity.get()) {
            if (TextUtils.isEmpty(timeFilterEntity.get().getShipmentEndTime())) {
                map.put("shipmentEndTime", "");
            } else {
                map.put("shipmentEndTime", Long.valueOf(timeFilterEntity.get().getShipmentEndTime()));
            }
            if (!TextUtils.isEmpty(timeFilterEntity.get().getShipmentTime())) {
                map.put("shipmentTime", Long.valueOf(timeFilterEntity.get().getShipmentTime()));
            } else {
                map.put("shipmentTime", "");
            }
        }

        if (LocationUtil.isOpenLocation(goodsHallListFragment.getContext())) {
            if (LocationUtil.getCurrentLongitude() != 0.00) {
                map.put("ipLongitude", LocationUtil.getCurrentLongitude());
                map.put("ipLatitude", LocationUtil.getCurrentLatitude());
            }
        }

        if (TextUtils.isEmpty(goodsType.get().getNo()) || goodsType.get().getNo().equals(DEFAULT_GOODS_TYPE)) {
            map.put("goodsTypeNo", "");
        } else {
            map.put("goodsTypeNo", goodsType.get().getNo());
        }
        if (TextUtils.isEmpty(goodsSecondType.get().getNo()) || goodsSecondType.get().getNo().equals(DEFAULT_GOODS_TYPE)) {
            map.put("secondGoodsTypeNo", "");
        } else {
            map.put("secondGoodsTypeNo", goodsSecondType.get().getNo());
        }

        //*********  2.1.5 新增参数：装货地半径以及发货地经纬度 *********//
        if (filterEntity.get() != null && filterEntity.get().getRadius() > 0) {
            map.put("radius", filterEntity.get().getRadius());
        } else {
            map.put("radius", 0);
        }

        if (goodsHallListFragment.searchLatLng != null) {
            map.put("searchLongitude", goodsHallListFragment.searchLatLng.longitude);
            map.put("searchLatitude", goodsHallListFragment.searchLatLng.latitude);
        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                map.put("provinceNo", "");
            } else {
                map.put("provinceNo", sendLocation.get().getProvinceNo());
            }

            if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                map.put("cityNo", "");
            } else {
                map.put("cityNo", sendLocation.get().getCityNo());
            }

            if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                map.put("districtNo", "");
            } else {
                map.put("districtNo", sendLocation.get().getAreaNo());
            }
        }

        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                map.put("destProvinceNo", "");
            } else {
                map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
            }
            if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {

                map.put("destCityNo", "");
            } else {
                map.put("destCityNo", purposeLocation.get().getCityNo());
            }
            if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                map.put("destDistrictNo", "");
            } else {
                map.put("destDistrictNo", purposeLocation.get().getAreaNo());
            }
        }

        map.put("freightOrder", filterEntity.get().getFreightSort());

        if ((filterEntity.get().getMinWeight() == null)) {
            map.put("minWeight", 0);
        } else {
            map.put("minWeight", Double.valueOf(filterEntity.get().getMinWeight()));
        }

        if (filterEntity.get().getMaxWeight() == null) {
            map.put("maxWeight", 0);
        } else {
            map.put("maxWeight", Double.valueOf(filterEntity.get().getMaxWeight()));
        }

        if ((filterEntity.get().getVolume() == 0)) {
            map.put("volume", 0);
        } else {
            map.put("volume", Double.valueOf(filterEntity.get().getVolume()));
        }

        if (filterEntity.get().getMaxVolume() == 0) {
            map.put("maxVolume", 0);
        } else {
            map.put("maxVolume", Double.valueOf(filterEntity.get().getMaxVolume()));
        }

        if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
            map.put("needVideo", "0");
        } else {
            map.put("needVideo", filterEntity.get().getNeedVideo());
        }

        String typeNos = "";
        if (null != filterEntity.get().getCarType() && filterEntity.get().getCarType().size() > 0) {
            for (GoodsInfoTypeEntity3 entity : filterEntity.get().getCarType()) {
                if (!TextUtils.isEmpty(entity.getNo())) {
                    typeNos += entity.getNo() + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(typeNos)) {
            typeNos = typeNos.substring(0, typeNos.length() - 1);
        }
        map.put("carTypeNos", typeNos);

        String lenNos = "";
        if (null != filterEntity.get().getLengthType() && filterEntity.get().getLengthType().size() > 0) {
            for (GoodsInfoTypeEntity3 entity : filterEntity.get().getLengthType()) {
                if (!TextUtils.isEmpty(entity.getNo())) {
                    lenNos += entity.getNo() + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(lenNos)) {
            lenNos = lenNos.substring(0, lenNos.length() - 1);
        }
        map.put("carLenNos", lenNos);

        if (filterEntity.get().getDestRadius() != null) {
            map.put("destRadius", filterEntity.get().getDestRadius());
        } else {
            map.put("destRadius", 0);
        }

        if (goodsHallListFragment != null && goodsHallListFragment.getActivity() != null)
            DialogHelper.showProgressDialog(goodsHallListFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getFilterSourceList(map).enqueue(new Callback<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> call, Response<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                getGoodsSuccess(response.body());
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                getGoodsFail(t);
            }
        });
    }

    public void getMapList(int pattern, String keyWord) {
        if (map == null) {
            map = new HashMap();
        } else {
            map.clear();
        }

        //封装请求参数
        map.put("keyWord", keyWord);
        //2.2.0.2 需求改版：//只有竞价货运才传pattern=1，其他情况（货运大厅）不传pattern，表示查全部
        if (pattern == 1) {
            map.put("pattern", 1);
        }
        //区别图查还是大厅
//        if (!isMap) {
//            map.put("pattern", pattern);
//        } else if (pattern == 1) {
//            map.put("pattern", 1);
//        }
        map.put("limit", 200);
        map.put("page", 1);

        if (null != timeFilterEntity.get()) {
            if (TextUtils.isEmpty(timeFilterEntity.get().getShipmentEndTime())) {
                map.put("shipmentEndTime", "");
            } else {
                map.put("shipmentEndTime", Long.valueOf(timeFilterEntity.get().getShipmentEndTime()));
            }
            if (!TextUtils.isEmpty(timeFilterEntity.get().getShipmentTime())) {
                map.put("shipmentTime", Long.valueOf(timeFilterEntity.get().getShipmentTime()));
            } else {
                map.put("shipmentTime", "");
            }
        }

        if (LocationUtil.isOpenLocation(goodsHallListFragment.getContext())) {
            if (LocationUtil.getCurrentLongitude() != 0.00) {
                map.put("ipLongitude", LocationUtil.getCurrentLongitude());
                map.put("ipLatitude", LocationUtil.getCurrentLatitude());
            }
        }

        if (TextUtils.isEmpty(goodsType.get().getNo()) || goodsType.get().getNo().equals(DEFAULT_GOODS_TYPE)) {
            map.put("goodsTypeNo", "");
        } else {
            map.put("goodsTypeNo", goodsType.get().getNo());
        }
        if (TextUtils.isEmpty(goodsSecondType.get().getNo()) || goodsSecondType.get().getNo().equals(DEFAULT_GOODS_TYPE)) {
            map.put("secondGoodsTypeNo", "");
        } else {
            map.put("secondGoodsTypeNo", goodsSecondType.get().getNo());
        }

        //*********  2.1.5 新增参数：装货地半径以及发货地经纬度 *********//
        if (filterEntity.get() != null && filterEntity.get().getRadius() > 0) {
            map.put("radius", filterEntity.get().getRadius());
        } else {
            map.put("radius", 0);
        }

        if (goodsHallListFragment.searchLatLng != null) {
            map.put("searchLongitude", goodsHallListFragment.searchLatLng.longitude);
            map.put("searchLatitude", goodsHallListFragment.searchLatLng.latitude);
        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                map.put("provinceNo", "");
            } else {
                map.put("provinceNo", sendLocation.get().getProvinceNo());
            }

            if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                map.put("cityNo", "");
            } else {
                map.put("cityNo", sendLocation.get().getCityNo());
            }

            if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                map.put("districtNo", "");
            } else {
                map.put("districtNo", sendLocation.get().getAreaNo());
            }
        }

        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                map.put("destProvinceNo", "");
            } else {
                map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
            }
            if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {

                map.put("destCityNo", "");
            } else {
                map.put("destCityNo", purposeLocation.get().getCityNo());
            }
            if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                map.put("destDistrictNo", "");
            } else {
                map.put("destDistrictNo", purposeLocation.get().getAreaNo());
            }
        }

        map.put("freightOrder", filterEntity.get().getFreightSort());

        if ((filterEntity.get().getMinWeight() == null)) {
            map.put("minWeight", 0);
        } else {
            map.put("minWeight", Double.valueOf(filterEntity.get().getMinWeight()));
        }

        if (filterEntity.get().getMaxWeight() == null) {
            map.put("maxWeight", 0);
        } else {
            map.put("maxWeight", Double.valueOf(filterEntity.get().getMaxWeight()));
        }

        if ((filterEntity.get().getVolume() == 0)) {
            map.put("volume", 0);
        } else {
            map.put("volume", Double.valueOf(filterEntity.get().getVolume()));
        }

        if (filterEntity.get().getMaxVolume() == 0) {
            map.put("maxVolume", 0);
        } else {
            map.put("maxVolume", Double.valueOf(filterEntity.get().getMaxVolume()));
        }

        if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
            map.put("needVideo", "0");
        } else {
            map.put("needVideo", filterEntity.get().getNeedVideo());
        }

        String typeNos = "";
        if (null != filterEntity.get().getCarType() && filterEntity.get().getCarType().size() > 0) {
            for (GoodsInfoTypeEntity3 entity : filterEntity.get().getCarType()) {
                if (!TextUtils.isEmpty(entity.getNo())) {
                    typeNos += entity.getNo() + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(typeNos)) {
            typeNos = typeNos.substring(0, typeNos.length() - 1);
        }
        map.put("carTypeNos", typeNos);

        String lenNos = "";
        if (null != filterEntity.get().getLengthType() && filterEntity.get().getLengthType().size() > 0) {
            for (GoodsInfoTypeEntity3 entity : filterEntity.get().getLengthType()) {
                if (!TextUtils.isEmpty(entity.getNo())) {
                    lenNos += entity.getNo() + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(lenNos)) {
            lenNos = lenNos.substring(0, typeNos.length() - 1);
        }
        map.put("carLenNos", lenNos);

        if (filterEntity.get().getDestRadius() != null && filterEntity.get().getDestRadius() > 0) {
            map.put("destRadius", filterEntity.get().getDestRadius());
        } else {
            map.put("destRadius", 0);
        }

        if (goodsHallListFragment != null && goodsHallListFragment.getActivity() != null)
            DialogHelper.showProgressDialog(goodsHallListFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getMapSourceList(map).enqueue(new Callback<BaseEntity<ProListEntity<List<MapSourcesEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<MapSourcesEntity>>>> call, Response<BaseEntity<ProListEntity<List<MapSourcesEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals("ok")) {
                    goodsHallListFragment.showMapList(response.body().getData().getList());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<MapSourcesEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

}
